﻿using System;
using System.Collections.Generic;
using Common.Devices.Comm.Model.Helper;
using Helper;

namespace Common.Devices.Comm.Model
{
    public class TcpServerInfo : CommParameter
    {
        public TcpServerInfo()
        {
            Port = 8000;
            Backlog = 1;
        }

        public TcpServerInfo(Uri uri)
        {
            SetParameter(uri);
        }

        public sealed override void SetParameter(Uri uri)
        {
            Port = uri.Port; 
            Backlog = int.Parse(uri.GetQueryParameter("Backlog")); 
        }

         
        [Property(PropertyType.Number, "端口", "8000")]
        public int Port { get; set; } 

        [Property(PropertyType.Number, "最大连接数", "1")]
        public int Backlog { get; set; }

        public override Uri ToUri()
        {
            //var uriBuilder = new UriBuilder("tcp://172.0.1.1:9999?baud=999&Stop=1&Odd=None");
            try
            {
                return new UriBuilder("TcpServer://0.0.0.0:" + Port + "?" + "Backlog=" + Backlog).Uri;
            }
            catch (Exception)
            {
                return new UriBuilder("TcpServer://0.0.0.0:8000?" + "Backlog=" + Backlog).Uri;

            }
        }

        public override string ToUriString()
        {
            return ToUri().ToString();
        }

        public override bool SetParameter(List<PropertyAttribute> parameter)
        {
            try
            {
                if (!string.IsNullOrEmpty(GetValue(parameter, "Port")))
                {
                    Port = Convert.ToInt32(GetValue(parameter, "Port"));
                }
                if (!string.IsNullOrEmpty(GetValue(parameter, "Backlog")))
                {
                    Backlog = Convert.ToInt32(GetValue(parameter, "Backlog"));
                }
                return true;
            }
            catch (Exception)
            {
                // ignored
            }

            return false;
        }
    }
}
